package com.smartinput.voice.controller

import com.mensanyun.kotool.util.executeQueryWithTry
import com.mensanyun.kotool.util.executeWithResult
import com.mensanyun.kotool.util.executeWithTry
import com.smartinput.voice.application.dto.*
import com.smartinput.voice.application.service.VoiceRecognitionService
import jakarta.validation.Valid
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

@RestController
@RequestMapping("/api/voice")
class VoiceController(
    private val voiceRecognitionService: VoiceRecognitionService
) {

    @PostMapping("/recognize", consumes = [MediaType.APPLICATION_OCTET_STREAM_VALUE])
    fun recognizeVoice(@RequestBody audioData: ByteArray) = executeWithResult {
        val recognizedText = voiceRecognitionService.processAudioStream(audioData)
        mapOf("text" to recognizedText)
    }

    @PostMapping("/recognize/file", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    fun recognizeVoiceFile(
        @RequestParam("audio") audioFile: MultipartFile,
        @RequestParam("deviceId") deviceId: String
    ) = executeWithResult {
        val principal = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication.principal
        val currentUserId = if (principal is org.springframework.security.core.userdetails.UserDetails) {
            principal.username
        } else {
            principal.toString()
        }
        
        val recognizedText = voiceRecognitionService.processAudioFile(
            userId = currentUserId,
            deviceId = deviceId,
            audioFile = audioFile
        )
        mapOf("text" to recognizedText)
    }

    /**
     * 开始实时语音识别会话
     */
    @PostMapping("/session/start")
    fun startVoiceSession() = executeWithResult {
        // 暂时返回成功，后续可通过VoiceRecognitionService管理会话
        mapOf(
            "success" to true,
            "message" to "语音识别会话已开始",
            "status" to "ready"
        )
    }

    /**
     * 获取当前会话状态
     */
    @GetMapping("/session/status")
    fun getSessionStatus() = executeWithResult {
        // 暂时返回默认状态，后续可通过VoiceRecognitionService获取
        mapOf(
            "isActive" to true,
            "status" to "ready"
        )
    }

    /**
     * 持续发送音频数据进行实时识别
     */
    @PostMapping("/session/audio", consumes = [MediaType.APPLICATION_OCTET_STREAM_VALUE])
    fun sendAudioToSession(@RequestBody audioData: ByteArray) = executeWithResult {
        // 使用设备ID或生成临时ID
        val deviceId = "mobile_${System.currentTimeMillis()}"
        val result = voiceRecognitionService.recognizeAudioRealTime(audioData, deviceId)
        mapOf(
            "success" to result.success,
            "text" to result.text,
            "confidence" to result.confidence,
            "error" to result.error
        )
    }

    /**
     * 结束语音识别会话
     */
    @PostMapping("/session/stop")
    fun stopVoiceSession() = executeWithResult {
        // 暂时返回成功，后续可通过VoiceRecognitionService管理会话
        mapOf(
            "success" to true,
            "message" to "语音识别会话已结束"
        )
    }

    @PostMapping("/records")
    fun saveVoiceRecord(@Valid @RequestBody request: VoiceSaveRequest) = executeWithTry {
        val principal = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication.principal
        val currentUserId = if (principal is org.springframework.security.core.userdetails.UserDetails) {
            principal.username
        } else {
            principal.toString()
        }
        
        voiceRecognitionService.saveVoiceRecord(
            userId = currentUserId,
            deviceId = request.deviceId,
            content = request.content,
            confidence = request.confidence
        )
    }

    @GetMapping("/records")
    fun getCurrentUserVoiceHistory(
        @RequestParam(defaultValue = "20") limit: Int
    ) = executeQueryWithTry {
        val principal = org.springframework.security.core.context.SecurityContextHolder.getContext().authentication.principal
        val currentUserId = if (principal is org.springframework.security.core.userdetails.UserDetails) {
            principal.username
        } else {
            principal.toString()
        }
        voiceRecognitionService.getVoiceRecordsByUser(currentUserId, limit)
    }

    @GetMapping("/history")
    fun getVoiceHistory(
        @RequestParam userId: String,
        @RequestParam(defaultValue = "20") limit: Int
    ) = executeQueryWithTry {
        voiceRecognitionService.getVoiceRecordsByUser(userId, limit)
    }
} 